import { createSlice } from "@reduxjs/toolkit"
import { request, setToken as _setToken, getToken, clearToken } from "@/utils"
import { LoginApi, getUserInfoApi } from "@/apis/user"
const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      state.token = ""
      state.userInfo = {}
      clearToken()
    },
  },
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await LoginApi(loginForm)
    dispatch(setToken(res.data.token))
    _setToken(res.data.token)
  }
}

const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoApi()
    dispatch(setUserInfo(res.data))
  }
}

const userReducer = userStore.reducer

export { fetchLogin, fetchUserInfo, clearUserInfo }
export default userReducer
